<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { FormInstance, FormRules, ElMessage } from "element-plus"
import { Search, Refresh } from "@element-plus/icons-vue"
// 接口
import { getRegulatorDataApi, createRegulatorDataApi } from "@/api/personnel/personnel-list/index"
import { type getRegulator } from "@/api/personnel/personnel-list/types/index"
import { usePagination } from "@/hooks/usePagination"

// 持久化
import { useTeamStore } from "@/store/modules/team"
import { useUserStore } from "@/store/modules/user"

defineOptions({
  name: "personnelList"
})
// 用户持久
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()
// 团队持久
const teamStore = useTeamStore()
console.log(userStore.username, "用户名字持久化数据")
const teamNameK = ref("")
const activeName = ref("first")

/**团队持久化数据获取 */
const teamList = ref<any>([])
// 页面加载优化
const loading = ref(true)
// 点击弹窗
const dialogVisible = ref<boolean>(false)
// 已完成查看详情
const dialogVisible1 = ref<boolean>(false)
// 验证表单
// #region
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<any>({
  id: 1,
  job: "",
  num: 1,
  education: "",
  exp: "",
  team: userStore.teamName,
  sex: "",
  maxAge: NaN,
  minAge: NaN,
  note: "",
  state: "",
  message: "",
  technology: ""
})
const rules = reactive<FormRules>({
  job: [{ required: true, trigger: "blur", message: "请输入需要的职位" }],
  num: [
    { required: true, message: "请填写人数" },
    { type: "number", message: "请输入数字" }
  ],
  team: [
    {
      required: true,
      message: "请选择团队",
      trigger: "change"
    }
  ]
})
// #endregion
// 新增按钮提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      createRegulatorDataApi({
        id: 1,
        job: ruleForm.job,
        num: ruleForm.num,
        education: ruleForm.education,
        exp: ruleForm.exp,
        team: ruleForm.team,
        sex: ruleForm.sex,
        maxAge: ruleForm.maxAge,
        minAge: ruleForm.minAge,
        note: ruleForm.note,
        state: "0",
        message: "",
        technology: ruleForm.technology
      }).then(() => {
        getAddRegulator()
        dialogVisible.value = false
        ElMessage.success("发布成功")
      })
      console.log("查看数据--------", ruleForm.job)
      console.log("查看数据--------", ruleForm.num)
    }
  })
}
// 清空表单数据
// 发布需求取消按钮并清空id和表单内容
const clearValidate = () => {
  ruleFormRef.value?.clearValidate()
}
// #region
const resetForm = () => {
  ruleForm.job = ""
  ruleForm.num = 1
  ruleForm.education = ""
  ruleForm.exp = ""
  ruleForm.sex = ""
  ruleForm.maxAge = 0
  ruleForm.minAge = 0
  ruleForm.note = ""
  ruleForm.state = ""
  ruleForm.message = ""
  ruleForm.technology = ""
  clearValidate()
}
// #endregion
// 查 列表数据
// #region 详情
const searchData = reactive({
  team: "",
  job: ""
})
const searchFormRef = ref<FormInstance | null>(null)
const tableData = ref<getRegulator[]>([])
const tableTotal = ref<number>()
const getAddRegulator = () => {
  getRegulatorDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    team: userStore.teamName,
    job: searchData.job,
    state: "1"
    // id: searchData.id || "",
  })
    .then((res: any) => {
      tableData.value = res.data.taskList
      tableTotal.value = res.data.total

      console.log(tableData.value, "页面所有数据")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getAddRegulator()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getAddRegulator()
  }
  paginationData.currentPage = 1
}
// 1
const handleSearch1 = () => {
  if (paginationData.currentPage === 1) {
    getAddRegulator1()
  }
  paginationData.currentPage = 1
}
const resetSearch1 = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getAddRegulator1()
  }
  paginationData.currentPage = 1
}
// 2
const handleSearch2 = () => {
  if (paginationData.currentPage === 1) {
    getAddRegulator2()
  }
  paginationData.currentPage = 1
}
const resetSearch2 = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getAddRegulator2()
  }
  paginationData.currentPage = 1
}
// 已完成
const tableData1 = ref<getRegulator[]>([])
const tableTotal1 = ref<number>()
const getAddRegulator1 = () => {
  getRegulatorDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    state: "3",
    team: userStore.teamName,
    job: searchData.job
    // id: searchData.id || "",
  })
    .then((res: any) => {
      tableData1.value = res.data.taskList
      tableTotal1.value = res.data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
// 未通过
const tableData2 = ref<getRegulator[]>([])
const tableTotal2 = ref<number>() // 总数
const getAddRegulator2 = () => {
  getRegulatorDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    job: searchData.job,
    state: "4"
  })
    .then((res: any) => {
      tableData2.value = res.data.taskList
      tableTotal2.value = res.data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
// #endregion
// 时间转换
function timestampToTime(timestamp: any) {
  // 时间戳为10位需*1000，时间戳为13位不需乘1000
  const date = new Date(timestamp)
  const Y = date.getFullYear() + "-"
  const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"
  const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "
  return Y + M + D
}
// 增
// 打开团队需求提示框
const addper = () => {
  dialogVisible.value = true
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getAddRegulator, { immediate: true })
watch([() => paginationData.currentPage, () => paginationData.pageSize], getAddRegulator1, { immediate: true })
watch([() => paginationData.currentPage, () => paginationData.pageSize], getAddRegulator2, { immediate: true })
/**监听team（pinia）缓存 */
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    teamList.value = newValue.flat()
  },
  { immediate: true }
)
/** E N D */

// 查看已完成的详情信息
const peoperMessage = ref<string>()
const addqiehuan = (res: any) => {
  dialogVisible1.value = true
  peoperMessage.value = res.message
  console.log(res, "---")
  console.log(peoperMessage.value, "---输入框")
}
// 下载
// const downLoad = () => {
//   downLoadOrderTable({
//     source: searchData.source,
//     department: searchData.department,
//     cardName: searchData.cardName,
//     orderOutId: searchData.orderOutId,
//     handleMobile: searchData.handleMobile,
//     cardId: searchData.cardId,
//     takeMobile: searchData.takeMobile,
//     sku: searchData.sku,
//     start: new Date(searchData.searchDate[0]).getTime() || "",
//     end: new Date(searchData.searchDate[1]).getTime() + 86400000 || "", //后端需要+一天时间戳
//     state: searchData.state || 0,
//     id: searchData.id,
//     superName: searchData.superName,
//     salesman: salesman1.value
//   }).then((res: any) => {
//     const blob = new Blob([res.data], {
//       type: "application/xlsx;charset=utf-8"
//     })
//     // console.log(res)
//     const downloadElement = document.createElement("a")
//     const href = window.URL.createObjectURL(blob)
//     downloadElement.href = href
//     downloadElement.download = "订单.xlsx"
//     document.body.appendChild(downloadElement)
//     downloadElement.click()
//     window.URL.revokeObjectURL(href)
//     dialogVisible3.value = false
//     formData1.download = ""
//   })
// }
</script>

<template>
  <div class="app-container">
    <el-tabs v-loading="loading" v-model="activeName" class="demo-tabs">
      <el-tab-pane label="未完成" name="first">
        <!-- 搜索 -->
        <el-card v-loading="loading" shadow="never" class="search-wrapper">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="team" label="归属团队" style="display: none">
              <el-input v-model.trim="searchData.team" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="job" label="职位">
              <el-input v-model.trim="searchData.job" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
            <el-button type="primary" @click="addper" class="box-card-top">发布需求</el-button>
            <!-- <el-tooltip content="下载">
              <el-button type="primary" class="XZ" :icon="Download" circle @click="downLoad" />
            </el-tooltip> -->
          </el-form>
        </el-card>
        <el-card class="box-card-center">
          <!-- 数据展示 -->
          <div class="table-center">
            <el-table :data="tableData">
              <!-- 用插槽替换时间戳转换为日期 -->
              <el-table-column label="日期" align="center">
                <template #default="scope">
                  {{ timestampToTime(scope.row.create) }}
                </template>
              </el-table-column>
              <el-table-column prop="team" label="归属团队" align="center" />
              <el-table-column prop="job" label="职位" align="center" />
              <el-table-column prop="num" label="人数" align="center" />
              <el-table-column prop="education" label="学历" align="center" />
              <el-table-column prop="exp" label="工作经验" align="center" />
              <el-table-column prop="sex" label="性别" align="center" />
              <el-table-column label="年龄" align="center">
                <template #default="scope"> {{ scope.row.minAge }}-{{ scope.row.maxAge }} </template>
              </el-table-column>
              <el-table-column prop="technology" label="专业要求" align="center" />
              <el-table-column prop="note" label="其他备注" align="center" />
            </el-table>
          </div>
          <!-- 分页器 -->
          <div class="pagination">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :page-size="paginationData.pageSize"
              :total="tableTotal"
              :currentPage="paginationData.currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="已完成情况" name="second">
        <!-- 搜索 -->
        <el-card v-loading="loading" shadow="never" class="search-wrapper">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="team" label="归属团队" style="display: none">
              <el-input v-model.trim="searchData.team" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="job" label="职位">
              <el-input v-model.trim="searchData.job" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch1">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch1">重置</el-button>
            </el-form-item>
            <el-button type="primary" @click="addper" class="box-card-top">发布需求</el-button>
          </el-form>
        </el-card>
        <el-card class="box-card-center">
          <div class="table-center">
            <el-table :data="tableData1">
              <!-- 用插槽替换时间戳转换为日期 -->
              <el-table-column label="日期" align="center">
                <template #default="scope">
                  {{ timestampToTime(scope.row.create) }}
                </template>
              </el-table-column>
              <el-table-column prop="team" label="归属团队" align="center" />
              <el-table-column prop="job" label="职位" align="center" />
              <el-table-column prop="num" label="人数" align="center" />
              <el-table-column prop="education" label="学历" align="center" />
              <el-table-column prop="exp" label="工作经验" align="center" />
              <el-table-column prop="sex" label="性别" align="center" />
              <el-table-column label="年龄" align="center">
                <template #default="scope"> {{ scope.row.minAge }}-{{ scope.row.maxAge }} </template>
              </el-table-column>
              <el-table-column prop="technology" label="专业要求" align="center" />
              <el-table-column label="状态" align="center">
                <template #default="scope">
                  <el-button v-if="scope.row.state == 3" link type="primary" size="small">已完成</el-button>
                </template>
              </el-table-column>
              <el-table-column label="信息详情" align="center">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="addqiehuan(scope.row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页器 -->
          <div class="pagination">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :page-size="paginationData.pageSize"
              :total="tableTotal1"
              :currentPage="paginationData.currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="未通过" name="noTG">
        <!-- 搜索 -->
        <el-card v-loading="loading" shadow="never" class="search-wrapper">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="team" label="归属团队" style="display: none">
              <el-input v-model.trim="searchData.team" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="job" label="职位">
              <el-input v-model.trim="searchData.job" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch2">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch2">重置</el-button>
            </el-form-item>
            <el-button type="primary" @click="addper" class="box-card-top">发布需求</el-button>
          </el-form>
        </el-card>
        <el-card class="box-card-center">
          <div class="table-center">
            <el-table :data="tableData2">
              <!-- 用插槽替换时间戳转换为日期 -->
              <el-table-column label="日期" align="center">
                <template #default="scope">
                  {{ timestampToTime(scope.row.create) }}
                </template>
              </el-table-column>
              <el-table-column prop="team" label="归属团队" align="center" />
              <el-table-column prop="job" label="职位" align="center" />
              <el-table-column prop="num" label="人数" align="center" />
              <el-table-column prop="education" label="学历" align="center" />
              <el-table-column prop="exp" label="工作经验" align="center" />
              <el-table-column prop="sex" label="性别" align="center" />
              <el-table-column label="年龄" align="center">
                <template #default="scope"> {{ scope.row.minAge }}-{{ scope.row.maxAge }} </template>
              </el-table-column>
              <el-table-column prop="technology" label="专业要求" align="center" />
              <el-table-column label="状态" align="center">
                <template #default="scope">
                  <el-button v-if="scope.row.state == 4" link type="primary" size="small">未通过</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页器 -->
          <div class="pagination">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :page-size="paginationData.pageSize"
              :total="tableTotal2"
              :currentPage="paginationData.currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 人事需求弹出框 -->
    <el-dialog v-model="dialogVisible" :model="ruleForm" @close="resetForm" title="新增需求" width="30%">
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules" label-width="120px">
        <el-form-item label="需要职位" prop="job">
          <el-input v-model.trim="ruleForm.job" />
        </el-form-item>
        <el-form-item label="需要人数" prop="num" placeholder="请选择学历">
          <el-input v-model.number="ruleForm.num" />
        </el-form-item>
        <el-form-item label="招聘学历">
          <el-select v-model="ruleForm.education" placeholder="请选择学历">
            <el-option label="高中" value="高中" />
            <el-option label="专科" value="专科" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验">
          <el-select v-model="ruleForm.exp" placeholder="请选择工作经验">
            <el-option label="1年以下工作经验" value="1年以下工作经验" />
            <el-option label="1-3年工作经验" value="1-3年工作经验" />
            <el-option label="3-5年工作经验" value="3-5年工作经验" />
            <el-option label="5年以上工作经验" value="5年以上工作经验" />
          </el-select>
        </el-form-item>
        <!-- 管理员能看到所有团队 -->
        <el-form-item v-if="userStore.teamName == teamNameK" label="归属团队" prop="team">
          <el-select v-model="ruleForm.team" placeholder="归属团队">
            <!-- 拿团队持久化 -->
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <!-- 哪一个账号是什么就看到什么 -->
        <el-form-item v-else prop="recruit" label="归属团队">
          <el-input v-model="ruleForm.team" disabled />
        </el-form-item>
        <!-- 分行 -->
        <el-form-item label="性别">
          <el-select v-model="ruleForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item prop="age" label="年龄限制" class="ageInput">
          <el-input
            type="number"
            v-model="ruleForm.minAge"
            placeholder="请输入最小年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
          <span style="display: inline-block; padding: 0 5px">至</span>
          <el-input
            type="number"
            v-model="ruleForm.maxAge"
            placeholder="请输入最大年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
        </el-form-item>
        <el-form-item label="专业要求" placeholder="专业要求">
          <el-input v-model="ruleForm.technology" />
        </el-form-item>
        <el-form-item label="其他备注">
          <el-input v-model="ruleForm.note" type="textarea" />
        </el-form-item>
        <!-- 表单提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--  -->
    <!-- 详情弹出框 -->
    <el-dialog v-model="dialogVisible1" :model="peoperMessage" title="详细信息" width="30%">
      <el-form label-width="120px">
        <el-form-item label="反馈详情">
          <el-input v-model="peoperMessage" disabled type="textarea" />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.box-card-top {
  margin-bottom: 20px;
}
.card-center-box {
  display: flex;
  justify-content: space-between;
}
.card-center-text {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.XZ {
  margin-top: -20px;
}
</style>
